import reducers from './reducers/levelsReducer'
import levelSaga from './sagas/levelsSaga'
import { getLevels } from './actions/levelsActions'
import { Level, LevelsActionTypes } from './types/levelsTypes'

const { ccclass, property } = cc._decorator
var store = null

@ccclass
export default class Levels extends cc.Component {
  @property(cc.ScrollView)
  levelScrollView = null

  @property(cc.Prefab)
  levelBtn = null

  loadLevelButtons(levels: Array<Level>) {
    // 销毁之前的数据
    this.levelScrollView.content.children.forEach((child: cc.Node) => {
      child.destroy()
    })
    levels.forEach((element, index) => {
      let btn = cc.instantiate(this.levelBtn)
      let levelButton = btn.getComponent('LevelButton')
      levelButton.label.string = levels[index].no
      levelButton.index = index
      this.levelScrollView.content.addChild(btn)
      btn.on('click', this.changeSceneButtonTap, this)
    })
    // cc.log(this.levelScrollView.content.children)
  }

  changeSceneButtonTap(button: cc.Button) {
    const levelButton = button.getComponent('LevelButton')
    this.getDataNode().current = levelButton.index
    cc.director.loadScene('Game')
  }

  getDataNode() {     // 获取 DataNode 脚本
    return cc.find('dataNode').getComponent('DataNode')
  }

  reload() {
    store.dispatch(getLevels() as LevelsActionTypes)     // 获取关卡数据
  }

  // LIFE-CYCLE CALLBACKS:
  onLoad() {
    const sagaMiddleware = ReduxSaga.default()
    store = Redux.createStore(reducers, Redux.applyMiddleware(sagaMiddleware))
    sagaMiddleware.run(levelSaga)

    store.subscribe(() => {     // 绑定UI
      const state = store.getState()
      if (state.levels) {
        this.getDataNode().levels = state.levels
        this.loadLevelButtons(state.levels)
      }
    })

    const levelsData = this.getDataNode().levels
    levelsData ? this.loadLevelButtons(levelsData) : this.reload()

    if (CC_WECHATGAME) {
      wx.showShareMenu()
      wx.onShareAppMessage(() => {
        return { 
          title: '一个小游戏Demo'
        }
      })
    }
  }

  // start () {}


}
